<template>
  <scroll-view :scroll-y="true" class="h-11/12 m-auto w-11/12">
    <uni-forms label-position="top">
      <RefrigeratorComponents
        v-for="(item, index) in formData"
        :key="index"
        :operatorDataItemList="item"
        :isEdit="isEdit"
        ref="childComp"
      />
    </uni-forms>
    <uni-card title="填报人姓名" extra="必填*">
      <uni-forms-item>
        <uni-easyinput :disabled="isEdit" v-model="name" />
      </uni-forms-item>
    </uni-card>
    <button
      @tap="submit"
      class="mb-10 w-2/3 rounded-xl"
      style="background-color: #5199ff"
      v-if="!isEdit"
    >
      提交
    </button>
  </scroll-view>
</template>

<script lang="ts" setup>
import RefrigeratorComponents from '@/components/RefrigeratorComponents/RefrigeratorComponents.vue';
import { createWorksTable, getRefrigeratorDetail } from '@/services/review';
import type { FormComponent, operatorDataList } from '@/services/types/review';
import type {
  submitFormComponent,
  submitIceBoxData,
} from '@/services/types/write';
import { submitIceBox } from '@/services/write';
import type { RefrigeratorComponentsInstance } from '@/types/component';
import { convertToString, groupArrayAndLastItem } from '@/utils/utils';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';
const formData = ref<FormComponent[][]>([]);
const otherArray = ref<FormComponent[]>([]);
// 获取携带的参数
const props = defineProps(['item']);
const operatorData = JSON.parse(
  decodeURIComponent(props.item),
) as operatorDataList;
const tianBaoRenXingMing = ref<FormComponent>();
const name = ref('');
// 是否可编辑
const isEdit = ref(false);
// 页面加载时执行
onLoad(async () => {
  // 判断是否有reportID参数
  if (operatorData.reportId) {
    if (operatorData.reportId === '0') {
      // 返回上一层
      uni.navigateBack();
      return;
    }
    // 有则表示是查看详情
    await viewDetailByReportId(operatorData.reportId);
  } else {
    // 没有则表示是创建表格
    await createForm(operatorData.formId);
  }
});
const childComp = ref<RefrigeratorComponentsInstance[]>([]);
/**
 * 提交数据函数
 */
const submitData = (
  formData: FormComponent[][],
  tianBaoRenXingMing: FormComponent,
  formId: string,
  unionId: string,
  unionType: number = 2, // 2表示首次提交4表示更改
): submitIceBoxData => {
  childComp.value.forEach((childComp, index) => {
    formData[index][0].componentValue = formData[index][0].defaultValue;
    formData[index][1].componentValue = childComp.data.xianShiWenDu;
    formData[index][2].componentValue = convertToString(
      childComp.data.xianShiWenDuImg,
    );
    formData[index][3].componentValue = childComp.data.zhongXinWenDu;
    formData[index][4].componentValue = convertToString(
      childComp.data.zhongXinWenDuImg,
    );
  });

  let formDataValue = ([] as FormComponent[]).concat(...formData);
  tianBaoRenXingMing.componentValue = name.value;
  formDataValue.push(tianBaoRenXingMing!);
  // 处理其他数据
  otherArray.value.forEach((item) => {
    formDataValue.unshift(item);
  });
  // 转换成提交数据格式
  let submitFormData = [] as submitFormComponent[];
  formDataValue.forEach((item) => {
    submitFormData.push({
      cameraRecognition: 0,
      componentId: item.componentId,
      componentType: item.componentType,
      componentValue: item.componentValue!,
      defaultValue: item.defaultValue || '',
      formMainId: 0,
      formName: '',
      imgUseAlbumEnable: false,
      isNa: false,
      isNaValue: false,
      isRed: false,
      isValidate: item.isValidate,
      isValidationStatistics: false,
      mId: 0,
      optionId: 0,
      options: [],
      optionTitle: '',
      prompt: '',
      textType: 0,
      title: item.title,
      validationExpression: '',
    });
  });
  const submitData: submitIceBoxData = {
    checkDate: '',
    formComponents: submitFormData,
    formId: formId,
    formName: '',
    id: 0,
    reporterDptName: '',
    reporterId: 0,
    reporterName: '',
    reportId: 0,
    reportReviewStatus: 0,
    serialNumber: '',
    statisticsPromptTemplate: '',
    unionId: unionId,
    unionType: unionType,
  };
  return submitData;
};
/**
 * 提交函数
 */
const submit = () => {
  uni.showModal({
    title: '确认提交？',
    content: '提交后将无法修改，请确认是否提交',
    success: function (res) {
      if (res.confirm) {
        const data = submitData(
          formData.value,
          tianBaoRenXingMing.value!,
          operatorData.formId,
          operatorData.id,
        );
        submitIceBox(data).then((res) => {
          if (res.msg === 'success') {
            uni.showToast({
              title: '提交成功',
              icon: 'success',
              duration: 1000,
            });

            // 跳转到上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1000);
          }
        });
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    },
  });
};
// 根据formId创建表单函数
const createForm = async (formId: string) => {
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await createWorksTable(formId);
  if (res.msg === 'success') {
    const [arr, otherArr] = handleOtherData(res.data.formComponents);
    otherArray.value = otherArr;
    const [groupedArray, lastArray] = groupArrayAndLastItem(arr) as [
      FormComponent[][],
      FormComponent[],
    ];
    tianBaoRenXingMing.value = lastArray[0];
    formData.value = groupedArray;
  }
  uni.hideLoading();
};
// 根据reportID查看详情函数
const viewDetailByReportId = async (reportId: string) => {
  uni.showLoading({
    title: '加载中...',
    mask: true,
  });
  const res = await getRefrigeratorDetail(reportId);
  if (res.msg === 'success') {
    const [arr, otherArr] = handleOtherData(res.data.formComponents);
    otherArray.value = otherArr;
    const [groupedArray, lastArray] = groupArrayAndLastItem(arr) as [
      FormComponent[][],
      FormComponent[],
    ];

    // 填写人姓名
    name.value = lastArray[0].componentValue!;
    formData.value = groupedArray;
    isEdit.value = true;
  }
  uni.hideLoading();
};

// 处理非冰箱相关数据
const handleOtherData = (data: FormComponent[]) => {
  const TITLE = [
    '冰箱编码',
    '冰箱显示温度',
    '食品取代物中心温度或测试水瓶中心温度',
    '填报人姓名',
  ];
  const arr = [] as FormComponent[];
  const otherArr = [] as FormComponent[];

  for (let i = 0; i < data.length; i++) {
    const item = data[i];
    if (TITLE.includes(item.title)) {
      arr.push(item);
    } else {
      otherArr.push(item);
    }
  }
  return [arr, otherArr];
};
</script>

<style lang="scss" scoped>
::v-deep.uni-card {
  .uni-card__header {
    .uni-card__header-extra {
      .uni-card__header-extra-text {
        color: #ff0000;
      }
    }
  }
}
</style>
